//
//  CheckVersion.m
//  ZXCommonProduct
//
//  Created by paeanSs on 16/5/25.
//  Copyright © 2016年 lzx. All rights reserved.
//

#import "CheckVersion.h"
#import "HDHTTPBaseModel.h"
#import "YJUpdateAlertView.h"
NSString const *iTnuesApi = @"http://itunes.apple.com/lookup";
#define kTestApp @"http://itunes.apple.com/lookup?id=350962117"  //新浪微博 app测试
@implementation CheckVersion
+ (instancetype)sharedCheckVersion
{
    static CheckVersion *sharedCheckVersion = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedCheckVersion = [[CheckVersion alloc]init];
    });
    
    return sharedCheckVersion;
}
+ (void )check_APP_UPDATE_WITH_APPID:(NSString *)appid
{
    __block id JSON = nil;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSError *dataError = nil;
        NSString *appURLAPI = [NSString stringWithFormat:@"%@checkVersion?bundleId=%@",YJBBaseURL,[YjbTool bundleId]];
        NSData *appData = [NSData dataWithContentsOfURL:[NSURL URLWithString:appURLAPI] options:0 error:&dataError];
        if (dataError) {
            //NSLog(@"appStore app版本信息请求错误！请重新尝试");
//            [self showAlertWithMessage:@"appStore app版本信息请求错误！请重新尝试"];
            return ;
        }
        JSON = [NSJSONSerialization JSONObjectWithData:appData options:0 error:nil];
        //NSLog(@"ddd : %@",JSON);
        
        if ([[JSON objectForKey:@"resultCount"] intValue] > 0) {
            NSString *remoteVersion = [[[JSON objectForKey:@"results"] objectAtIndex:0] objectForKey:@"version"];
            NSString *releaseNotes = [[[JSON objectForKey:@"results"] objectAtIndex:0] objectForKey:@"releaseNotes"];
            NSString *trackURL = [[[JSON objectForKey:@"results"] objectAtIndex:0] objectForKey:@"trackViewUrl"];
            [[NSUserDefaults standardUserDefaults] setObject:trackURL forKey:@"KK_THE_APP_UPDATE_URL"];
            //NSLog(@"%@ %@ %@",remoteVersion,releaseNotes,trackURL);
            
            NSString *localVersion = [YjbTool get_LocalApp_Version];
            
            
            
            
            //以"."分隔数字然后分配到不同数组
            NSArray * serverArray = [remoteVersion componentsSeparatedByString:@"."];
            NSArray * localArray = [localVersion componentsSeparatedByString:@"."];
            
            for (int i = 0; i < serverArray.count; i++) {
                
                //以服务器版本为基准，判断本地版本位数小于服务器版本时，直接返回（并且判断为新版本，比如服务器1.5.1 本地为1.5）
                if(i > (localArray.count -1)){
                    //有新版本，提示！
                    [[CheckVersion sharedCheckVersion] newVersionUpdate:remoteVersion notes:releaseNotes];
                    break;
                }
                //有新版本，服务器版本对应数字大于本地
                if ( [serverArray[i] intValue] > [localArray[i] intValue]) {
                    //有新版本，提示！
                    [[CheckVersion sharedCheckVersion] newVersionUpdate:remoteVersion notes:releaseNotes];
                    break;
                } else if ([localArray[i] intValue] > [serverArray[i] intValue]) {
                    break;
                }
            }
        }
        else
        {
            //NSLog(@"appStore 无app信息，请检查您的 app id");
//            [self showAlertWithMessage:@"appStore 无此app信息，请检查您的 app id"];
            return ;
        }
        
        
    });
    
}



+(void)updateApp {
    
    #ifdef DEBUG
//       [self showAlertWithMessage:@"测试更新" size:@"0.1MB"];
    #endif
  

    NSDictionary *param = @{@"action":@"find_new_version"};
    [HDHTTPBaseModel sendRequestWith:@"" params:param finishedBlock:^(BaseResponser *responser, NSError *error) {
        
        if (!error) {
            
            if ([responser.data isKindOfClass:[NSDictionary class]]) {
                NSString *des = responser.data[@"description"];
                NSString *size = responser.data[@"size"];
                [self showAlertWithMessage:des size:size];
            }
            
        }
       
        
    }];

}


+(void)showAlertWithMessage:(NSString *)messages size:(NSString *)size {
    NSString *content = [NSString stringWithFormat:@"本次更新大小:%@\n%@",size,messages];
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"游戏数据更新" message:content preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"更新" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        YJUpdateAlertView *alert = [[YJUpdateAlertView alloc] initWithFrame:[UIScreen mainScreen].bounds];
        [[UIApplication sharedApplication].keyWindow addSubview:alert];
        NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(timerAction:) userInfo:alert repeats:YES];
        
    }];
    [alert addAction:action];
    [[YjbTool activityViewController] presentViewController:alert animated:YES completion:nil];
   
}

+ (void)timerAction:(NSTimer *)timer{
   
    YJUpdateAlertView *alert = timer.userInfo;
    CGFloat progress = alert.progress;
    
    alert.textMsg = @"正在为您下载资源";
    CGFloat radomProgress = ((arc4random()%50 )+1) / 100.0f + progress;
    
    if (radomProgress >= 1.0f) {
        radomProgress = 1.0f;
    }
    [alert resetUpdateAlertViewWithProgress:radomProgress];
    if (radomProgress == 1.0f) {
        
        [timer invalidate];
        timer = nil;
        alert.hidden = YES;
        [alert resetUpdateAlertViewWithProgress:0];
        alert.textMsg = @"正在为您解压资源（解压资源不耗流量）";
        NSTimer *otherTimer = [NSTimer scheduledTimerWithTimeInterval:0.2 target:self selector:@selector(nextTimerAction:) userInfo:alert repeats:YES];
       
    }

}

+ (void)nextTimerAction:(NSTimer *)timer{
    
    YJUpdateAlertView *alert = timer.userInfo;
    alert.hidden = NO;
    CGFloat progress = alert.progress;
    
    alert.textMsg = @"正在为您解压资源（解压资源不耗流量）";
    CGFloat radomProgress = ((arc4random()%10 )+1) / 100.0f + progress;
    
    if (radomProgress >= 1.0f) {
        radomProgress = 1.0f;
    }
    [alert resetUpdateAlertViewWithProgress:radomProgress];
    if (radomProgress == 1.0f) {
        [alert removeFromSuperview];
        alert = nil;
        [timer invalidate];
        timer = nil;
        
        dispatch_async(dispatch_get_main_queue(), ^{
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:nil message:@"更新已完成" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
            [alert show];
            
#if !__has_feature(objc_arc)
            [alert release];
#endif
        });
    }
    
}

+ (void)showAlertWithMessage:(NSString *)messages
{
    dispatch_async(dispatch_get_main_queue(), ^{
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"版本更新提示" message:messages delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        
#if !__has_feature(objc_arc)
        [alert release];
#endif
    });
    
}

- (void)newVersionUpdate:(NSString *)version notes:(NSString *)releaseNotes
{
    dispatch_async(dispatch_get_main_queue(), ^{
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:[NSString stringWithFormat:@"新版本 %@",version] message:releaseNotes delegate:self cancelButtonTitle:nil otherButtonTitles:@"发现新版本", nil];
        [alert show];
        
#if !__has_feature(objc_arc)
        [alert release];
#endif
    });
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex==0) {
        //NSString *apiUrl = @"https://itunes.apple.com/us/app/wei-bo/id350962117?mt=8&uo=4";
        //apiUrl = @"itms-apps://itunes.apple.com/cn/app/wei-bo/id350962117?mt=8";
        NSString *theAppURL = [[NSUserDefaults standardUserDefaults] objectForKey:@"KK_THE_APP_UPDATE_URL"];
        NSURL *appStoreURL = [NSURL URLWithString:theAppURL];
        [[UIApplication sharedApplication] openURL:appStoreURL];
    }
}
@end
